import argparse
import hashlib
import os

from PIL import Image, ImageDraw, ImageFont


def hex_to_rgb(hex_color):
    """ 将 HEX 颜色转换为 RGB 颜色 """
    hex_color = hex_color.lstrip('#')  # 移除 '#' 符号（如果有）
    return tuple(int(hex_color[i:i + 2], 16) for i in (0, 2, 4))


def draw_triangle(draw):
    # 定义三角形的三个顶点坐标
    triangle = [(0, 150), (100, 100), (30, 50)]
    fill = hex_to_rgb('#44cef6')
    # 绘制填充三角形
    draw.polygon(triangle, fill=fill)


def create_text_avatar(text, path, size=200):
    text = text.strip()
    if len(text) == 0:
        print("Text can't be empty")
        return

    if path == '':
        path = './'

    full_path = os.path.join(path, md5(path) + '.png')

    img = Image.new("RGBA", (size, size), (0, 0, 0, 0))  # 创建透明背景
    draw = ImageDraw.Draw(img)

    left_up = (0, 0)  # 左上角坐标
    right_down = (size, size)  # 右下角坐标
    draw.ellipse([left_up, right_down], fill=(255, 100, 0, 255))
    font_size = size // 3
    try:
        font = ImageFont.truetype("YuFanZhenSu.otf", font_size)
    except IOError:
        font = ImageFont.load_default()  # 如果找不到字体，使用默认字体
    box = draw.textbbox((0, 0), text, font=font)
    # 计算文字居中的位置
    text_width = box[2] - box[0]
    text_height = box[3] - box[1]
    text_x = (size - text_width) // 2
    text_y = (size - text_height) // 2
    # draw.rectangle((text_x, text_y, text_width + text_x, text_height + text_y), fill=(255, 100, 0, 255))

    draw_triangle(draw)
    # 绘制文字
    draw.text((text_x, text_y), text, font=font, fill=(255, 255, 255))

    img.save(full_path)
    img.show()


def md5(input_string):
    # 创建hash对象，并选择算法为MD5
    md5_hasher = hashlib.md5()
    # 更新hash对象
    md5_hasher.update(input_string.encode('utf-8'))
    # 获取十六进制表示的MD5值
    return md5_hasher.hexdigest()


def main():
    parser = argparse.ArgumentParser(description='头像生成')
    parser.add_argument('--text', '-t', type=str, help='请输入用于生成头像的文本')
    parser.add_argument('--path', '-p', type=str, help='请提供头像生成路径', default='')
    args = parser.parse_args()
    # 生成 200x200 的透明背景圆形渐变（红色 → 橙色）
    create_text_avatar(args.text, args.path, size=128)


if __name__ == '__main__':
    main()
